package com.itps.fileservice.config;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Configuration
public class StaticResourceConfig implements WebMvcConfigurer {

    @Value("${file.upload.dir:${user.home}/uploads/}")
    private String uploadDir;

    /**
     * 应用启动时确保上传基础目录存在，避免写入失败。
     */
    @PostConstruct
    public void initUploadDir() {
        File baseDir = new File(uploadDir);
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }
    }

    /**
     * 将 /files/** 映射到本地文件系统上传目录，便于前端通过返回的 URL 直接访问。
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String normalizedPath = normalizePath(uploadDir);
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:" + normalizedPath);
    }

    /**
     * 规范化路径，统一分隔符并追加末尾斜杠。
     */
    private String normalizePath(String path) {
        if (path == null || path.isEmpty()) {
            return "./uploads/";
        }
        String p = path.replace("\\", "/");
        return p.endsWith("/") ? p : p + "/";
    }
}

